package com.xtaller.lazy.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.xtaller.lazy.Cache;
import com.xtaller.lazy.lib.annotation.Permission;
import com.xtaller.lazy.lib.bean.JWTResult;
import com.xtaller.lazy.lib.convert.J;
import com.xtaller.lazy.lib.convert.P;
import com.xtaller.lazy.lib.convert.S;
import com.xtaller.lazy.lib.kit.InterceptorUtil;
import com.xtaller.lazy.lib.kit.JwtUtil;
import com.xtaller.lazy.util.CacheUtil;
import io.jsonwebtoken.Claims;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

/**
 * @version V1.0
 * @author: Taller
 * @date: 2019-04-03
 * @Description:
 */
@Component
public class InterceptorPermission implements HandlerInterceptor {
    private P p = new P(this.getClass());
    @Autowired private CacheUtil cacheUtil;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        response.setHeader("Content-type", "text/html;charset=UTF-8");

        Permission permission = InterceptorUtil.getMethod(handler)
                        .getAnnotation(Permission.class);
        if (permission != null){
            var access_token = request.getHeader("token");
            JWTResult jwt = JwtUtil.validateJWT(access_token);
            Claims claims = jwt.getClaims();

            var key = S.apppend("user-auth-", claims.getId());
            var auths = JSONObject.parseArray(cacheUtil.getVal(key));

            if(auths == null || auths.size() == 0){
                response.setStatus(403);
                response.getWriter().write(J.s2r("当前缓存信息丢失请按f5重新刷新一下页面"));
                return false;
            }
            var auth = permission.authorities();
            if(!auths.contains(auth)){
                response.setStatus(403);
                response.getWriter().write(J.s2r("您无此功能操作权限"));
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
